<template>
  <div>
    姓名: <input v-model.trim="from.name" type="text" /><br />
    年龄: <input v-model.number="from.age" type="text" /><br />
    性别:
    <select v-model="from.gender">
      <option value="男">男</option>
      <option value="女">女</option></select
    ><br />
    <button @click="add">添加</button>
    <button @click="modify">修改</button>
    <br />
    <table border>
      <thead>
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in arr" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="del(item.id)">删除</button>&nbsp;
            <button @click="edl(item.id)">编辑</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      from: {
        name: "",
        age: "",
        gender: "",
        id: "",
      },
      arr: [
        { id: 11, name: "Tom", gender: "男", age: 19 },
        { id: 22, name: "Jone", gender: "女", age: 21 },
      ],
    };
  },
  methods: {
    add() {
      const { name, age, gender } = this.from;
      if (name === "" || age === "" || gender === "")
        return alert("请输入数据");
      this.arr.push({
        name,
        age,
        gender,
        id: Date.now(),
      });
      this.from = {};
    },
    edl(id) {
      const obj = this.arr.find((item) => item.id === id);
      this.from = { ...obj };
    },
    modify() {
      const id = this.from.id;
      const obj = this.arr.find((item) => item.id === id);
      obj.name = this.from.name;
      obj.age = this.from.age;
      obj.gender = this.from.gender;
      this.from = {};
    },
    del(id) {
      const index = this.arr.findIndex((item) => item.id === id);
      this.arr.splice(index, 1);
    },
  },
};
</script>

<style scoped>
table {
  /* border: 1px solid black; */
  border-collapse: collapse;
}
td,
th {
  padding: 10px;
}
</style>
